package com.xxx.chat.server.handler;

import com.xxx.chat.message.ChatRequestMessage;
import com.xxx.chat.message.ChatResponseMessage;
import com.xxx.chat.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 私聊请求处理handler
 * SimpleChannelInboundHandler<T>可以只监听感兴趣的类型的消息
 */
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        // 消息接受者
        String to = msg.getTo();
        // 获取消息接收者channel
        Channel channel = SessionFactory.getSession().getChannel(to);
        // 判断是否在线（channel是否存在）
        if (channel != null) { // 在线
            channel.writeAndFlush(new ChatResponseMessage(msg.getFrom(), msg.getContent()));
        } else {  // 不在线
            ctx.writeAndFlush(new ChatResponseMessage(false, "对方用户不存在或者不在线"));
        }
    }
}
